/*
 * XMLTag.cpp
 *
 *  Created on: Jul 14, 2013
 *      Author: Dan
 */

#include "XMLTag.h"

namespace monkeyXML {

XMLTag::~XMLTag() {
	//std::cout<<"Tag destructo\n";
}

std::string XMLTag::getTag() {
	return theTag;
}

XMLTag::XMLTag(const std::string& aTag, const std::vector<std::string>& aLabels,
		const std::vector<std::string>& aValues) throw (std::length_error) {
	if (aLabels.size() != aValues.size()) {
		std::length_error le = std::length_error("Error creating a new XMLTag"
				" using different sized arrays for attributes.");
		throw le;
	} else {
		theTag = aTag;
		for (unsigned i = 0; i < aValues.size(); i++) {
			attrib a;
			a.label = aLabels[i];
			a.value = aValues[i];
			theAttributes.push_back(a);
		}
	}
}

XMLTag::XMLTag(const std::string& aTagWithAtts) {
	int index = 1;
	bool inQuotes = false;

	char current = aTagWithAtts[index];

	while (current != '>' && current != '/' && current != ' ') {
		theTag += current;
		current = aTagWithAtts[++index];
	}

	if (current != '>' && current != '/') {
		do {
			current = aTagWithAtts[++index];
		} while (current == ' ' && current == '\n');
	}

	while (current != '>' && current != '/') {
		attrib att;

		while (current == ' ' || current == '\n') {
			current = aTagWithAtts[++index];
		}

		while (current != '=' && current != ' ') {
			att.label += current;
			current = aTagWithAtts[++index];
		}

		while (current != '=') {
			current = aTagWithAtts[++index];
		}

		do {
			current = aTagWithAtts[++index];
		} while (current == ' ' || current == '\n');

		while ((current != ' ' && current != '\n' && current != '/'
				&& current != '>') || inQuotes) {
			if (current == '"') {
				inQuotes = !inQuotes;
			} else {
				att.value += current;
			}
			current = aTagWithAtts[++index];
		}
		theAttributes.push_back(att);
	}
}

XMLTag::XMLTag(const XMLTag& another) {
	this->theTag = another.theTag;
	this->theAttributes = another.theAttributes;
}

std::string XMLTag::toString() {
	std::string theFullTag;
	theFullTag.append(theTag);
	if (!theAttributes.empty()) {
		std::list<attrib>::iterator i = theAttributes.begin();
		do {
			theFullTag += " ";
			theFullTag += i->label;
			theFullTag += "=";
			theFullTag += i->value;
			++i;
		} while (i != theAttributes.end());
	}
	return theFullTag;
}

std::string XMLTag::readAttrib(const std::string& anAttrib) {
	bool found = false;
	std::list<attrib>::iterator i = theAttributes.begin();
	std::string result;
	while (i != theAttributes.end() && !found) {
		if (i->label.compare(anAttrib) == 0) //equal strings
				{
			result = i->value;
		}
		++i;
	}
	return result;
}

} /* namespace monkeyXML */
